import {
  cartesian3ToDegrees, // 笛卡尔坐标转为经纬度
  getDistanceH, // 获取两个笛卡尔坐标的水平距离
  getArea, // 计算多边形面积
  getMiddlePoint, // 计算多边形中点位置（笛卡尔坐标）
  getMousePosition, // 鼠标左键点击坐标
  getMouseMovePosition // 鼠标移动坐标
} from './tool'

// gis底图内外网判断变量(out--外网,inner--内网)
let env = process.env.VUE_APP_MAP_LINE

// CesiumDefaultToken(个人申请，后续需替换公司申请的token)
export const CesiumDefaultToken =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxNmUyMTM5ZC0zZWY1LTQ4MjMtYTRkMi05ODM4YWQxY2I4NTUiLCJpZCI6ODA3OTYsImlhdCI6MTY4MDA4MjM4Mn0.sCyjEZLj2T8IOiM3EyLqQ8p2YSZaFsb9OBma3vNp1W4'

// 星图云Token(个人申请，后续需替换公司申请的token)
export const XingTuToken =
  'e8933b32700e5c2b00f5eb2fa42628842af7a60a2c6142d1d65f1f8ed592ce12'

export const SHUO_HUANG_SITE = ['电厂线', '神池南', '贾象']

// 获取朔黄Server服务的provider WMTS
export var MapServer = {
  // 需带服务参数
  china_navi: 'CHINA_NAVI', // 全国影像缓存
  basemap_blue_cache: 'BaseMap_blue_cache', // 全国影像缓存—10级
  basemap_blue_cache_v1: 'BaseMap_blue_cache_v1', // 基础底图深色缓存
  basemap_cache: 'BaseMap_cache', // 基础底图浅色缓存
  sh_yx_navi: 'sh_yx_navi', // 朔黄沿线影像切片缓存 L19
  // 不需带服务参数
  sh_navi: 'SH_NAVI', // 朔黄沿线影像 L19
  basemap_write: 'BaseMap_write', // 基础底图浅色
  basemap_blue: 'BaseMap_blue' // 基础底图深色
}
export var getServerWMTSProvider = serverName => {
  const key = localStorage.getItem('mapToken')
  const url = `http://10.48.37.32:8080/OneMapServer/rest/services/${serverName}/MapServer/WMTS?token=${key}`
  const Identifier =
    serverName == MapServer.sh_yx_navi
      ? 'SH_sh_yx_navi'
      : serverName == MapServer.basemap_cache
        ? 'SH_BaseMap_cache2'
        : serverName == MapServer.basemap_blue_cache_v1
          ? 'SH_BaseMap_blue_cache'
          : serverName == MapServer.china_navi
            ? 'SH_CHINA_NAVI_T1'
            : serverName == MapServer.basemap_blue_cache
              ? 'SH_QGYX_L10_CACHE_V1'
              : ''
  const obj1 = {
    url: url,
    layer: serverName,
    style: 'default',
    tilingScheme: new Cesium.WebMercatorTilingScheme()
  }
  const obj2 = {
    tileMatrixSetID: 'default028mm',
    format: 'image/png',
    wkid: 3857,
    Identifier: Identifier
  }
  let obj
  let maximumLevel = 17
  if (serverName === MapServer.basemap_blue_cache) {
    maximumLevel = 10
  } else if (
    serverName === MapServer.sh_navi ||
    serverName === MapServer.sh_yx_navi
  ) {
    maximumLevel = 19
  }
  if (Identifier) {
    obj = { ...obj1, ...obj2, maximumLevel }
  } else {
    obj = { ...obj1, maximumLevel }
  }
  // console.log("obj", obj);
  return new Cesium.WebMapTileServiceImageryProvider(obj)
}
// cesium默认配置
export const cesiumDefaultConfig = {
  shouldAnimate: true,
  shadows: false,
  baseLayerPicker: false,
  geocoder: false,
  homeButton: false,
  fullscreenButton: false,
  navigationHelpButton: false,
  sceneModePicker: false,
  timeline: false,
  animation: false,
  selectionIndicator: false,
  infoBox: false,
  contextOptions: {
    webgl: {
      alpha: true,
      depth: false,
      stencil: true,
      antialias: true,
      premultipliedAlpha: true,
      preserveDrawingBuffer: true,
      failIfMajorPerformanceCaveat: true
    },
    allowTextureFilterAnisotropic: true
  },
  imageryProvider:
    env === 'inner'
      ? getServerWMTSProvider(MapServer.china_navi)
      : new Cesium.UrlTemplateImageryProvider({
        url:
            'https://tiles{s}.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&token=' +
            XingTuToken,
        subdomains: '123',
        maximumLevel: 18
      })
}

export const initCesium = async(id = 'cesium-container') => {
  return new Promise(resolve => {
    const viewer = new Cesium.Viewer(id, cesiumDefaultConfig)
    viewer.scene.globe.showGroundAtmosphere = true
    viewer.scene.postProcessStages.fxaa.enabled = false
    if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
      viewer.resolutionScale = window.devicePixelRatio
    }
    viewer.scene.preRender.addEventListener(function() {
      viewer.camera._suspendTerrainAdjustment = false
    })
    viewer.cesiumWidget.creditContainer.style.display = 'none'
    resolve(viewer)
  })
}

export const destroyCesium = viewer => {
  viewer.entities.removeAll()
  viewer.imageryLayers.removeAll()
  viewer.destroy()
  viewer = null
}

// 添加朔黄沿线影像切片缓存图层(影像)
export const addLayer = viewer => {
  const imageryProvider = getServerWMTSProvider(MapServer.sh_yx_navi)
  const layer = viewer.imageryLayers.addImageryProvider(imageryProvider, 6)
  return [layer]
}

// 添加星图云图层(影像)
export const addXTLayer1 = viewer => {
  env = process.env.VUE_APP_MAP_LINE
  if (env === 'inner') {
    // 内网图层
    const imageryProvider = getServerWMTSProvider(MapServer.china_navi)
    const layer = viewer.imageryLayers.addImageryProvider(imageryProvider, 1)
    return [layer]
  } else {
  // 星图云图层--开发环境使用
    const token = XingTuToken
    const imageryProvider = new Cesium.UrlTemplateImageryProvider({
      url:
        'https://tiles{s}.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&token=' +
        token,
      subdomains: '123',
      maximumLevel: 18
    })
    const layer0 = viewer.imageryLayers.addImageryProvider(imageryProvider)
    const imageryProvider1 = new Cesium.UrlTemplateImageryProvider({
      url:
        'https://tiles{s}.geovisearth.com/base/v1/cia/{z}/{x}/{y}?format=webp&token=' +
        token,
      subdomains: '123',
      maximumLevel: 18
    })
    const layer1 = viewer.imageryLayers.addImageryProvider(imageryProvider1, 1)
    return [layer0, layer1]
  }
}
// 添加星图云图层(矢量)
export const addXTLayer2 = viewer => {
  env = process.env.VUE_APP_MAP_LINE
  if (env === 'inner') {
    // 内网图层
    const imageryProvider = getServerWMTSProvider(MapServer.basemap_cache)
    const layer = viewer.imageryLayers.addImageryProvider(imageryProvider, 2)
    return [layer]
  }else {
    // 星图云图层--开发环境使用
    const token = XingTuToken
    const imageryProvider = new Cesium.UrlTemplateImageryProvider({
      url:
        'https://tiles{s}.geovisearth.com/base/v1/vec/{z}/{x}/{y}?format=webp&token=' +
        token,
      subdomains: '123',
      maximumLevel: 18
    })
    const layer = viewer.imageryLayers.addImageryProvider(imageryProvider, 2)
    return [layer]
  }
}
// 添加星图云地形,开发环境使用
export const addXTTerrain = viewer => {
  const token = XingTuToken
  const terrainProvider = new Cesium.CesiumTerrainProvider({
    url: 'https://tiles1.geovisearth.com/base/v1/terrain?token=' + token
  })
  viewer.terrainProvider = terrainProvider
}

export const defaultView = viewer => {
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(114.983297, 38.693297, 800000)
  })
}
// 添加线路及点位
export const loadSiteEntities = (viewer, siteList) => {
  const siteEntityList = []
  let sitePointPos = []
  let siteLine1 = null
  let siteLine2 = null
  function fontSize(res) {
    const clientWidth =
      window.innerWidth ||
      document.documentElement.clientWidth ||
      document.body.clientWidth ||
      window.screen.width
    if (!clientWidth) {
      return res
    }
    const fontSize = clientWidth / 1920
    return res * fontSize
  }
  if (viewer && siteList) {
    // TODO:考虑取中间点(endLongitude,endLatitude),(startLongitude,startLatitude)
    siteList.forEach((s, i) => {
      const labelIsTop = i % 2 === 0 ? 1 : -1
      const labelLeft = (-1 * (s.name.length * fontSize(24))) / 2
      const lon1 = s.endLongitude
      const lat2 = s.endLatitude
      let flag2 = false
      if (lon1 && lat2) {
        flag2 = true
      }
      if (flag2) {
        const opt = {
          siteId: s.siteId,
          name: s.name,
          position: Cesium.Cartesian3.fromDegrees(
            Number(s.endLongitude),
            Number(s.endLatitude)
          ),
          billboard: {
            width: fontSize(36),
            height: fontSize(36),
            image: '/static/icon/site.png',
            sizeInMeters: false,
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            // pixelOffset: new Cesium.Cartesian2(0, 0),
            scaleByDistance: new Cesium.NearFarScalar(1000, 1, 1.0e7, 0.2),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
              0,
              3000000
            ),
            scale: 1,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            eyeOffset: new Cesium.Cartesian3(0, 0, -10)
          },
          label: {
            text: s.name,
            fillColor: Cesium.Color.fromCssColorString('#fff'),
            font: `normal ${fontSize(24)}px MicroSoft YaHei`,
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            pixelOffset: new Cesium.Cartesian2(
              labelLeft,
              labelIsTop * fontSize(36)
            ),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            scaleByDistance: new Cesium.NearFarScalar(1000, 1, 1.0e7, 0.1),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
              0,
              1000000
            ),
            showBackground: true,
            backgroundColor: Cesium.Color.fromCssColorString(
              '#1890ff'
            ).withAlpha(0.8),
            backgroundPadding: new Cesium.Cartesian2(fontSize(6), fontSize(3))
          }
        }
        const ent = viewer.entities.add(opt)
        siteEntityList.push(ent)
        sitePointPos = [
          ...sitePointPos,
          Number(s.endLongitude),
          Number(s.endLatitude)
        ]
      }
    })
    siteLine1 = viewer.entities.add({
      name: 'siteLine1',
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArray(sitePointPos),
        width: 7,
        material: Cesium.Color.BLACK,
        clampToGround: true,
        zIndex: 1
      }
    })
    siteLine2 = viewer.entities.add({
      name: 'siteLine2',
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArray(sitePointPos),
        width: 5,
        material: new Cesium.PolylineDashMaterialProperty({
          color: Cesium.Color.WHITE
        }),
        clampToGround: true,
        zIndex: 2
      }
    })
  }
  return {
    siteEntityList,
    siteLine1,
    siteLine2
  }
}

export const removeEnt = (viewer, entList) => {
  if (viewer && entList) {
    entList.forEach(e => {
      viewer.entities.remove(e)
    })
  }
}

export const mapChange = (viewer, type) => {
  if (type === '3D') {
    viewer.scene.morphTo3D(0)
  } else if (type === '2D') {
    viewer.scene.morphTo2D(0)
  }
}

let mouseMove = false
let distancePointEntities = []
let distanceLineEntities = []
let distanceResultEntities = []
let areaPointEntities = []
let areaLineEntities = []
let areaResultEntities = []
let lineEnt1 = null
let areaEnt1 = null
export const Measure = {
  viewer: null,
  handler: null,
  clickIndex: 0,
  positions: [],
  currentPosition: [],
  isMeasure: false,
  type: 'distance',
  init(viewer) {
    this.viewer = viewer
    this.handler = null
    this.clickIndex = 0
    this.positions = []
    this.currentPosition = []
    this.isMeasure = false
  },
  // 开始测量type='distance'距离，type='area'面积
  start(type = 'distance') {
    this.type = type
    this.isMeasure = true
    mouseMove = false
    this.positions = []
    this.currentPosition = []
    if (this.handler) {
      this.unRegisterEvents()
      this.handler.destroy()
      this.handler = null
    }
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    this.viewer._element.style.cursor = 'pointer'
    this.registerEvents()

    switch (type) {
      case 'distance':
        this.createLineEntity1()
        break
      case 'area':
        this.createPolygon1()
        break

      default:
        throw new Error('type类型错误')
        break
    }
  },
  end() {
    this.unRegisterEvents()
    if (this.type === 'distance') {
      this.createLineEntity2()
      this.viewer.entities.remove(lineEnt1)
      lineEnt1 = null
      this.distanceResult()
    } else {
      if (this.positions.length > 2) {
        this.createPolygon2()
        this.areaResult()
      } else {
        areaPointEntities.forEach(e => {
          this.viewer.entities.remove(e)
        })
        areaPointEntities = []
      }
      this.viewer.entities.remove(areaEnt1)
      areaEnt1 = null
    }
    this.isMeasure = false
    this.clickIndex = 0
    this.viewer._element.style.cursor = 'default'
  },
  distanceResult() {
    let allDistance = 0
    for (let i = 0; i < this.positions.length - 1; i++) {
      const distance = getDistanceH(this.positions[i], this.positions[i + 1])
      const p1 = cartesian3ToDegrees(this.positions[i])
      const p2 = cartesian3ToDegrees(this.positions[i + 1])
      const x = (p1[0] + p2[0]) / 2
      const y = (p1[1] + p2[1]) / 2
      const z = (p1[2] + p2[2]) / 2
      const p3 = [x, y, z]
      const resultLabel = {
        position: p3,
        label: distance + '米'
      }
      this.createResultLabel(resultLabel)
      allDistance += distance
    }
    const p4 = cartesian3ToDegrees(this.positions[this.positions.length - 1])
    const resultLabel = {
      position: p4,
      label: '总长度:' + allDistance.toFixed(2) + '米'
    }
    this.createResultLabel(resultLabel)
  },
  areaResult() {
    const area = getArea(this.positions)

    const middlePoint = getMiddlePoint(this.positions)

    const resultLabel = {
      position: middlePoint,
      label: area + '平方米'
    }
    this.createResultLabel(resultLabel)
  },
  createResultLabel(resultLabel) {
    if (!this.viewer) return
    let pos = null
    if (this.type === 'distance') {
      pos = Cesium.Cartesian3.fromDegrees(...resultLabel.position)
    } else {
      pos = resultLabel.position
    }
    const ent = this.viewer.entities.add({
      position: pos,
      label: {
        text: resultLabel.label,
        fillColor: Cesium.Color.fromCssColorString('#fff'),
        font: `normal ${fontSize(24)}px MicroSoft YaHei`,
        horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
        verticalOrigin: Cesium.VerticalOrigin.CENTER,
        pixelOffset: new Cesium.Cartesian2(0, -20),
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        scaleByDistance: new Cesium.NearFarScalar(5, 1, 3e6, 0.5),
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
          0,
          3000000
        ),
        showBackground: true,
        backgroundColor: Cesium.Color.fromCssColorString('#233146').withAlpha(
          0.7
        ),
        backgroundPadding: new Cesium.Cartesian2(2, 2)
      }
    })
    if (this.type === 'distance') {
      distanceResultEntities.push(ent)
    } else {
      areaResultEntities.push(ent)
    }
  },
  registerEvents() {
    this.leftClickEvent()
    this.rightClickEvent()
    this.mouseMoveEvent()
  },
  unRegisterEvents() {
    if (!this.handler) return
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
  },
  // 左键点击事件
  leftClickEvent() {
    if (!this.handler) return
    this.handler.setInputAction(e => {
      const position = getMousePosition(this.viewer, e.position)
      if (!position) return
      const lon = Cesium.Math.toDegrees(position.longitude)
      const lat = Cesium.Math.toDegrees(position.latitude)
      const hei = position.height
      this.currentPosition = [lon, lat, hei]
      const p = Cesium.Cartesian3.fromDegrees(...this.currentPosition)
      this.positions[this.clickIndex] = p
      this.clickIndex++
      mouseMove = false
      this.createPointEntity()
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
  },

  // 鼠标移动事件
  mouseMoveEvent() {
    if (!this.handler) return
    this.handler.setInputAction(e => {
      if (!this.isMeasure) return
      this.viewer._element.style.cursor = 'pointer'
      const position = getMouseMovePosition(this.viewer, e.endPosition)
      if (!position) return
      this.handleMoveEvent(position)
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
  },

  // 处理鼠标移动
  handleMoveEvent(position) {
    if (this.positions.length < 1) return
    const twoPosition = position
    this.positions[this.clickIndex] = twoPosition
    mouseMove = true
  },
  // 右键事件
  rightClickEvent() {
    if (!this.handler) return
    this.handler.setInputAction(e => {
      if (this.isMeasure) {
        if (mouseMove) {
          this.positions.pop()
        }
        this.unRegisterEvents()
        this.end()
      }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  },
  createPointEntity() {
    if (!this.viewer) return
    const ent = this.viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(...this.currentPosition),
      point: {
        color: Cesium.Color.CORAL,
        pixelSize: 5,
        outlineColor: Cesium.Color.CORNSILK,
        outlineWidth: 2,
        scaleByDistance: new Cesium.NearFarScalar(1000, 1, 100000, 0.4),
        disableDepthTestDistance: 1000
      }
    })
    distancePointEntities.push(ent)
  },
  createLineEntity1() {
    if (!this.viewer) return
    lineEnt1 = this.viewer.entities.add({
      polyline: {
        positions: new Cesium.CallbackProperty(e => {
          return this.positions
        }, false),
        width: 2,
        material: Cesium.Color.YELLOW,
        clampToGround: false,
        depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
          color: Cesium.Color.YELLOW
        })
      }
    })
  },
  createLineEntity2() {
    if (!this.viewer) return
    var lineEnt2 = this.viewer.entities.add({
      polyline: {
        positions: this.positions,
        width: 2,
        material: Cesium.Color.YELLOW,
        clampToGround: false,
        depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
          color: Cesium.Color.YELLOW
        })
      }
    })
    distanceLineEntities.push(lineEnt2)
  },
  createPolygon1() {
    if (!this.viewer) return
    areaEnt1 = this.viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(e => {
          return new Cesium.PolygonHierarchy(this.positions)
        }, false),
        material: Cesium.Color.YELLOW.withAlpha(0.4),
        perPositionHeight: true
        // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 1000000),
        // disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    })
  },
  createPolygon2() {
    if (!this.viewer) return
    var areaEnt2 = this.viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(this.positions),
        material: Cesium.Color.YELLOW.withAlpha(0.4),
        perPositionHeight: true
        // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 1000000),
        // disableDepthTestDistance: Number.POSITIVE_INFINITY
      },
      polyline: {
        positions: this.positions.concat(this.positions[0]),
        width: 1,
        material: new Cesium.PolylineDashMaterialProperty({
          color: Cesium.Color.YELLOW
        }),
        depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
          color: Cesium.Color.YELLOW
        }),
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
          0,
          1000000
        )
      }
    })
    distanceLineEntities.push(areaEnt2)
  },
  clear() {
    if (this.viewer) {
      if (lineEnt1) {
        this.viewer.entities.remove(lineEnt1)
      }
      distancePointEntities.forEach(e => {
        this.viewer && this.viewer.entities.remove(e)
      })

      distanceLineEntities.forEach(e => {
        this.viewer && this.viewer.entities.remove(e)
      })

      distanceResultEntities.forEach(e => {
        this.viewer && this.viewer.entities.remove(e)
      })
      if (areaEnt1) {
        this.viewer.entities.remove(areaEnt1)
      }
      areaPointEntities.forEach(e => {
        this.viewer && this.viewer.entities.remove(e)
      })

      areaLineEntities.forEach(e => {
        this.viewer && this.viewer.entities.remove(e)
      })

      areaResultEntities.forEach(e => {
        this.viewer && this.viewer.entities.remove(e)
      })
    }
    lineEnt1 = null
    distancePointEntities = []
    distanceLineEntities = []
    distanceResultEntities = []
    areaEnt1 = null
    areaPointEntities = []
    areaLineEntities = []
    areaResultEntities = []
    this.reset()
  },
  reset() {
    if (this.handler) {
      this.unRegisterEvents()
      this.handler.destroy()
      this.handler = null
    }

    this.isMeasure = false

    this.clickIndex = 0
    this.positions = []
    this.currentPosition = []
    this.viewer._element.style.cursor = 'default'
  },
  destroyed() {
    this.clear()
    this.viewer = null
  }
}

export const scaleMap = (viewer, type, range = [70, 20000000]) => {
  const center = getMapCenterLocation(viewer)
  if (center !== '-1') {
    const x = center[0]
    const y = center[1]
    const z = center[2]
    const height = z
    let minH = height / 1.5
    let maxH = height * 1.5
    if (minH < range[0]) {
      minH = range[0]
    }
    if (maxH > range[1]) {
      maxH = range[1]
    }
    if (type === 'BIG' && minH >= range[0] && minH <= range[1]) {
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(x, y, minH),
        duration: 1.0
      })
    } else if (type === 'SMALL' && maxH >= range[0] && maxH <= range[1]) {
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(x, y, maxH),
        duration: 1.0
      })
    }
  }
}

export const getMapCenterLocation = viewer => {
  const zoom = getMapCenter(viewer)
  const height = viewer.camera.positionCartographic.height // 当前视高
  if (zoom !== '-1') {
    const longitude = zoom.longitude * (180 / Math.PI)
    const latitude = zoom.latitude * (180 / Math.PI)
    return [longitude, latitude, height]
  } else {
    return '-1'
  }
}
export const getMapCenter = viewer => {
  const centerResult = viewer.camera.pickEllipsoid(
    new Cesium.Cartesian2(
      viewer.canvas.clientWidth / 2,
      viewer.canvas.clientHeight / 2
    )
  )
  const curPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(
    centerResult
  )
  return curPosition
  // const windowPosition = new Cesium.Cartesian2(
  //   viewer.container.clientWidth / 2,
  //   viewer.container.clientHeight / 2
  // );
  // if (windowPosition) {
  //   const pickRay = viewer.scene.camera.getPickRay(windowPosition);
  //   if (pickRay) {
  //     const pickPosition = viewer.scene.globe.pick(pickRay, viewer.scene);
  //     if (pickPosition) {
  //       const pickPositionCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(
  //         pickPosition
  //       );
  //       return pickPositionCartographic;
  //     } else {
  //       return "-1";
  //     }
  //   } else {
  //     return "-1";
  //   }
  // } else {
  //   return "-1";
  // }
}

// 卷帘对比
export const splitLayer = {
  viewer: null,
  leftLayer: null,
  rightLayer: null,
  handler: null,
  sliderId: '',
  init(viewer, sliderId) {
    this.viewer = viewer
    this.leftLayer = null
    this.rightLayer = null
    this.handler = null
    this.sliderId = sliderId
  },
  start() {
    const layers = this.viewer.imageryLayers
    const viewer = this.viewer
    let layer1
    let layer2
    env = process.env.VUE_APP_MAP_LINE
    if (env === 'out') {
      // 星图云的矢量和影像，开发时使用
      const token = XingTuToken
      layer1 = new Cesium.UrlTemplateImageryProvider({
        url:
          'https://tiles{s}.geovisearth.com/base/v1/vec/{z}/{x}/{y}?format=webp&token=' +
          token,
        subdomains: '123',
        maximumLevel: 18
      })
      layer2 = new Cesium.UrlTemplateImageryProvider({
        url:
          'https://tiles{s}.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&token=' +
          token,
        subdomains: '123',
        maximumLevel: 18
      })
    } else if (env === 'inner') {
      // 内网底图
      layer1 = getServerWMTSProvider(MapServer.basemap_cache)
      layer2 = getServerWMTSProvider(MapServer.china_navi)
    }

    this.leftLayer = layers.addImageryProvider(layer1, 4)
    this.rightLayer = layers.addImageryProvider(layer2, 5)
    this.leftLayer.splitDirection = Cesium.ImagerySplitDirection.LEFT
    this.rightLayer.splitDirection = Cesium.ImagerySplitDirection.RIGHT
    const sliderDom = document.getElementById(this.sliderId)
    sliderDom.style.display = 'block'
    viewer.scene.imagerySplitPosition =
      sliderDom.offsetLeft / sliderDom.parentElement.offsetWidth

    this.handler = new Cesium.ScreenSpaceEventHandler(sliderDom)

    let moveActive = false
    function move(movement) {
      if (!moveActive || !sliderDom || !sliderDom.parentElement) {
        return
      }

      const relativeOffset = movement.endPosition.x
      const splitPosition =
        (sliderDom.offsetLeft + relativeOffset) /
        sliderDom.parentElement.offsetWidth
      let end = 0
      if (splitPosition <= 0) {
        end = 0.01
      } else if (splitPosition >= 0.99) {
        end = 0.99
      } else {
        end = splitPosition
      }
      // sliderDom.style.left = 100.0 * splitPosition + "%";
      // viewer.scene.imagerySplitPosition = splitPosition;
      sliderDom.style.left = 100.0 * end + '%'
      viewer.scene.imagerySplitPosition = end
    }

    this.handler.setInputAction(function() {
      moveActive = true
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN)
    this.handler.setInputAction(function() {
      moveActive = true
    }, Cesium.ScreenSpaceEventType.PINCH_START)

    this.handler.setInputAction(move, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    this.handler.setInputAction(move, Cesium.ScreenSpaceEventType.PINCH_MOVE)

    this.handler.setInputAction(function() {
      moveActive = false
    }, Cesium.ScreenSpaceEventType.LEFT_UP)
    this.handler.setInputAction(function() {
      moveActive = false
    }, Cesium.ScreenSpaceEventType.PINCH_END)
  },
  end() {
    const slider = document.getElementById(this.sliderId)
    slider.style.display = 'none'
    this.viewer.imageryLayers.remove(this.leftLayer)
    this.viewer.imageryLayers.remove(this.rightLayer)
    this.leftLayer = null
    this.rightLayer = null
    if (this.handler) {
      this.handler.destroy()
      this.handler = null
    }
  }
}

export const fontSize = res => {
  const clientWidth =
    window.innerWidth ||
    document.documentElement.clientWidth ||
    document.body.clientWidth ||
    window.screen.width
  if (!clientWidth) {
    return res
  }
  const fontSize = clientWidth / 1920
  return res * fontSize
}

//  添加列车图标
export const loadTrainEntity = viewer => {
  if (!viewer) return
  const trainEnt = viewer.entities.add({
    type: 'TRAIN',
    position: Cesium.Cartesian3.fromDegrees(0, 0),
    show: false,
    billboard: {
      image: '/static/gis/train.png',
      width: fontSize(48),
      height: fontSize(48),

      sizeInMeters: false,
      verticalOrigin: Cesium.VerticalOrigin.CENTER,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      // pixelOffset: new Cesium.Cartesian2(0, 0),
      scaleByDistance: new Cesium.NearFarScalar(1000, 1, 1.0e7, 0.2),
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 3000000),
      scale: 1,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      disableDepthTestDistance: Number.POSITIVE_INFINITY
      // eyeOffset: new Cesium.Cartesian3(0, 0, -10)
    }
  })
  return trainEnt
}
